<template>
  <div class="call-center-detail-info" >
    <div class="main">
      <h4>{{$t('callcenter.callInfo')}}</h4>
      <div class="call-info">
        <p>{{ $t('common.label.recordId') }}：<span>{{callDetail.recordId}}</span></p>
        <p>{{ $t('common.label.callDuration') }}：<span>{{callDetail.talkTime >>0 |fmt_h_m_s}}</span></p>
        <p>{{ $t('common.label.agentName') }}：
          <span class="user-card-triggle" v-user="callDetail.agentUserId">
            <template v-if="isOpenData && callDetail.agentStaffId">
              <open-data type="userName" :openid="callDetail.agentStaffId"></open-data>
            </template>
            <template v-else>
              <span>{{callDetail.agentName}}</span>
            </template>
          </span>
        </p>
        <p>{{ $t('common.label.agentCount') }}：<span>{{callDetail.agent}}</span></p>
      </div>
      <div class="call-info">
        <p>{{ $t('common.label.dialPhone') }}：<span>{{callDetail.dialPhone}}</span>
          <template v-if="callDetail.dialPhone && hasCallAuth ">
            <biz-call-icon :value="callDetail.dialPhone" v-track="$track.formatParams('CALL_OUT')" />
          </template>
        </p>
        <p>{{ $t('common.label.callStartTime') }}：<span>{{callDetail.beginTime}}</span></p>
        <p>{{ $t('common.label.ringTime') }}：<span>{{callDetail.ring}}</span></p>
      </div>
      <div class="call-info">
        <p>{{ $t('common.label.callFromArea') }}：<span>{{callDetail.attribution}}</span></p>
        <p>{{ $t('common.label.callEndTime') }}：<span>{{callDetail.endTime}}</span></p>
        <p></p>
      </div>
      <div class="call-info">
        <span style="color: #999;">{{ $t('common.label.recordFile') }}：</span>
        <audio :src="callDetail.recordFile" controls="controls" preload style="height:36px;outline: 0;" @play="audioPlay('record')"></audio>
      </div>
      <div class="call-info mar-t-10">
        <p>
          <span style="color: #999;">{{ $t('common.label.hasLeaveMessage') }}：</span>
          <span>{{callDetail.hasLeaveMessage==1? $t('common.base.yes'): $t('common.base.no')}}</span>
        </p>
      </div>
      <div class="call-info">
        <span style="color: #999;">{{ $t('common.label.leaveMessageFileUrl') }}：</span>
        <audio :src="callDetail.leaveMessageFileUrl" controls="controls" preload style="height:36px;outline: 0;" @play="audioPlay('leaveMessage')"></audio>
      </div>
      <h4 class="customer-info-header">{{ $t('callcenter.callDetailPage.linkmanInfo') }}</h4>
      <div class="customer-info">
        <!-- <audio src="http://65.ierge.cn/12/186/372266.mp3" controls="controls" preload style="height:42px;"></audio>  -->
        <template v-if="unknown || showLinkmanName">
          <p v-if="unknown">{{ $t('common.label.unFinishEvent') }}：<span class="unFinishEvent">{{contact.unfinishedEventCount}}</span></p>
          <div v-if="showCreateUser" class="customer-container" v-loading.fullscreen.lock="loadingPage">
            <form @submit.prevent="submit" class="base-form" v-if="init">
              <customer-edit-form :fields="fields" v-model="form" ref="form" />
              <button type="submit" :disabled="submitting || pending" class="btn btn-primary">{{$t('common.base.save')}}</button>
              <button type="button" class="btn btn-ghost mar-l-10" @click="cancelCreate">{{$t('common.base.cancel')}}</button>
            </form>
          </div>
          <div v-else>
            <p>{{ $t('common.label.customer') }}：<span>{{ contact.name || $t('common.base.unknown') }}</span></p>
            <p>{{ $t('common.label.contact') }}：<span>{{ (contact.linkman && contact.linkman.name) || $t('common.base.unknown') }}</span></p>
            <template v-if="allowCreateCustomer">
              <el-button type="primary" @click="toCreateCustomer">{{$t('common.button.createCustomer')}}</el-button>
              <el-button type="plain-third" @click="saveDialog" style="margin-left:10px;">{{$t('common.button.addToExistCustomer')}}</el-button>
            </template>
          </div>
        </template>
        <template v-else>
          <p>{{ $t('common.label.customer') }}：<a href="" class="customer-info-a" style="cursor: pointer;" @click.stop.prevent="createCustomerTab(contact.id)">{{contact.name}}</a></p>
          <p>{{ $t('common.label.contact') }}：<span v-if="contact.linkman">{{contact.linkman.name}}</span></p>
          <p>{{ $t('common.label.area') }}：<span v-if="contact.customerAddress">{{contact.customerAddress.adProvince}}</span></p>
          <p>{{ $t('common.label.addressDetail') }}：<span v-if="contact.customerAddress">{{contact.customerAddress.adAddress}}</span></p>
          <p>{{ $t('common.label.principalName') }}：
            <template v-if="isOpenData">
              <open-data type="userName" :openid="contact.customerManagerStaffId"></open-data>
            </template>
            <template v-else>
              <span>{{contact.customerManagerName}}</span>
            </template>
          </p>
          <p>{{ $t('common.label.serviceDepartment') }}：<span>{{dealTags(contact.tags)}}</span></p>
          <p v-if="_isShowTaskModule">
              {{ $t('common.label.unFinishTask') }}：
              <span class="unFinishTask">
                  {{contact.unfinishedTaskCount}}
              </span>
          </p>
          <p>{{ $t('common.label.unFinishEvent') }}：<span class="unFinishEvent">{{contact.unfinishedEventCount}}</span></p>
        </template>
      </div>
      <h4 class="customer-info-header" v-if="_isShowTaskModule || showLinkmanName">
          {{$t('common.base.relationTask')}}
        <template v-if="unknown || (showLinkmanName && !bindProductId)">
          <el-tooltip :content="$t('callcenter.callDetailPage.tips1')" placement="top" :enterable="false">
            <el-dropdown trigger="click">
              <el-button type="info" plain disabled>{{$t('common.button.createTask')}}</el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item v-for="type in taskTypes" :key="type.id">
                  <div class="link-of-dropdown" @click="createTask(type.id)">{{type.name}}</div>
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </el-tooltip>
        </template>
        <template v-else>
          <el-dropdown trigger="click">
            <!-- 如果已经有关联工单了显示关联工单单号 -->
            <template v-if="taskBusinessNo">
              <a href="" class="customer-info-a" style="cursor: pointer;" @click.stop.prevent="createTaskTab(contact.taskBindRecord.wordId)">{{taskBusinessNo}}</a>
            </template>
            <template v-else>
              <el-button type="primary" :disabled="!allowCreateTask" v-track="$track.formatParams('TO_CREATE_TASK')">{{$t('common.button.createTask')}}</el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item v-for="type in taskTypes" :key="type.id">
                  <div class="link-of-dropdown" @click="createTask(type.id)">{{type.name}}</div>
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>

          </el-dropdown>
        </template>
      </h4>
      <h4 class="customer-info-header">{{$t('common.base.relationEvent')}}
        <template v-if="unknown && !showLinkmanName">
          <el-tooltip :content="$t('callcenter.callDetailPage.tips1')" placement="top" :enterable="false">
            <el-dropdown trigger="click">
              <el-button type="info" plain disabled>{{$t('common.button.createEvent')}}</el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item v-for="event in eventTypes" :key="event.id">
                  <div class="link-of-dropdown" @click="createEvent(event.id)">{{event.name}}</div>
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </el-tooltip>
        </template>
        <template v-else>
          <el-dropdown trigger="click">
            <!-- 如果已经有关联事件了显示关联事件编号 -->
            <template v-if="eventBusinessNo">
              <a href="" class="customer-info-a" style="cursor: pointer;" @click.stop.prevent="createEventTab(contact.eventBindRecord.wordId)">{{eventBusinessNo}}</a>
            </template>
            <template v-else>
              <el-button type="primary" :disabled="!allowCreateEvent" v-track="$track.formatParams('TO_CREATE_EVENT')">{{$t('common.button.createEvent')}}</el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item v-for="event in eventTypes" :key="event.id">
                  <div class="link-of-dropdown" @click="createEvent(event.id)">{{event.name}}</div>
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </h4>
    </div>
    <div class="right">
      <el-tabs v-model="rightActiveTab">
        <el-tab-pane :label="$t('common.base.serviceRemark')" name="1"> </el-tab-pane>
        <el-tab-pane :label="$t('common.tabs.productDerail')" name="2"> </el-tab-pane>
        <el-tab-pane v-if="satisfactionGray" :label="$t('common.tabs.im.tabs3')" name="3"> </el-tab-pane>
      </el-tabs>
      <!-- <h4 style="font-size: 16px;margin-bottom: 20px;padding-top: 8px;">{{$t('common.base.serviceRemark')}}</h4> -->
      
      <!-- 服务备注 -->
      <div v-show="rightActiveTab === '1'" style="height:calc(100% - 50px)">
        <ServiceNotes ref="ServiceNotes" :customer-id="customerId" :id="query.id" :biz-type="2" :biz-no="callDetail.recordId" module="呼叫中心" :phone="callDetail.dialPhone" :is-show-operate-row="allowEdit"/>
      </div>
      <!-- 产品信息 -->
      <div v-show="rightActiveTab === '2'" class="messagebox-content">
        <!-- <callcenter-product-table></callcenter-product-table> -->
        <callcenter-product-info :call-detail="callDetail" @submit="e => bindProductId = e"></callcenter-product-info>
      </div>
      <!-- 客户评价 -->
      <div v-show="rightActiveTab === '3'" class="messagebox-content">
        <iframe v-if="satisfactionGray && callDetail.evaluated === 1" id="imIframe" :src="iframeUrl" height="98%" width="100%"/>
        <div v-else class="default">
          <no-data-view-new :notice-msg="$t('im.detail.tips1')"></no-data-view-new>
        </div>
      </div>

    </div>

    <!-- 添加到现有客户的对话框 -->
    <el-dialog :title="$t('callcenter.callDetailPage.addToExistCustomer')" :visible.sync="saveDialogVisible" width="30%" @close="saveDialogClosed">
      <!-- 内容主体区域 -->
      <el-form :model="saveForm" :rules="saveFormRules" ref="saveFormRef" label-position="top">
        <el-form-item :label="$t('common.label.customer')" prop="customer">
          <customer-select v-model="customer" :field="customerField" :remote-method="searchCustomer" :update-customer="updateCustomer" :placeholder="$t('common.placeholder.selectCustomer')"></customer-select>
          <!-- <el-input v-model="saveForm.name"></el-input> -->
        </el-form-item>
        <el-form-item :label="$t('common.label.contact')" prop="name">
          <el-input v-model="saveForm.name" :placeholder="$t('common.placeholder.inputContact')"></el-input>
        </el-form-item>
        <el-form-item :label="$t('common.label.contactPhone')" prop="phone">
          <el-input v-model="saveForm.phone" disabled></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="saveDialogVisible = false">{{ $t('common.button.cancel') }}</el-button>
        <el-button type="primary" @click="saveUser">{{ $t('common.button.confirm') }}</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import { isOpenData, openAccurateTab } from '@src/util/platform'
import {parse} from '@src/util/querystring';
import FormMixin from '@src/component/form/mixin/form'
import CustomerEditForm from '../../customer/components/CustomerEditForm.vue'
import * as FormUtil from '@src/component/form/util'
import * as util from '../../customer/util/customer'
import platform from '@src/platform'
import * as CallCenterApi from '@src/api/CallCenterApi'
import BaseCallPhone from 'src/component/common/BaseCallPhone/index.vue'
import { getRootWindow } from '@src/util/dom';
import { getCustomerList } from '@src/api/CustomerApi'
/* mixin */
import ThemeMixin from '@src/mixins/themeMixin/index.ts'
import ServiceNotes from '@src/modules/im/imDetail/ServiceNotes.vue';

import AuthMixin from '@src/mixins/authMixin'
/** util */
import AuthUtil from '@src/util/auth';
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import { formatAddress } from 'pub-bbx-utils';
/* version control mixin */
import { VersionControlTaskMixin } from '@src/mixins/versionControlMixin'
// components
import CallcenterProductTable from '@src/modules/callcenter/component/CallcenterProductTable.vue';
import CallcenterProductInfo from '@src/modules/callcenter/component/CallcenterProductInfo.vue';
import NoDataViewNew from '@src/component/common/NoDataViewNew';

let query;
export default {
  name: 'call-detail',
  inject: ['initData'],
  mixins: [ThemeMixin, AuthMixin, VersionControlTaskMixin],
  data() {
    return {
      query:{},
      isOpenData,
      callDetail:{},
      unknown: true,
      contact: {},
      showCreateUser: false,
      submitting: false,
      pending: false,
      loadingPage: false,
      form: {},
      init: false,
      customerId: '',
      saveDialogVisible: false,
      saveForm: {
        name: '',
        phone: ''
      },
      saveFormRules: {
        customer:[
          {
            required:true,
            validator:(rule, value, callback)=>{
              if(this?.customer[0]?.value){
                callback();
              }else{
                callback(new Error(this.$t('common.placeholder.selectCustomer')));
              }
            },
            trigger: 'blur'
          },
        ],
        name: [{ required: true, message: this.$t('common.placeholder.inputContact'), trigger: 'blur' }],
        phone:[{ required: true, message: this.$t('common.placeholder.inputContactPhone2'), trigger: 'blur' }]
      },
      customer: [],
      customerField: {
        isSystem: 1,
        fieldName: 'customer',
        displayName: this.$t('common.label.customer'),
        formType: 'customer',
        defaultValue: null,
        isNull: 0,
        isSearch: 0,
        placeHolder: null
      },
      remarkList: [],
      showAddRemarkForm:false,
      categoryList: [],
      cascaderProps: {
        value: 'id',
        label: 'name',
        children: 'children'
      },
      selectedKeys: [],
      ruleForm: {
        sortId: '',
        status: '',
        remark: ''
      },
      rules: {
        status: [{ required: true, message: this.$t('common.validate.validateResolveStatus'), trigger: 'blur' }]
      },
      rightActiveTab: '1',
      iframeUrl: '',
      showLinkmanName: false,
      bindProductId: '', // 绑定了产品展示新建工单按钮
    }
  },
  computed: {
    satisfactionGray() {
      const RootWindow = getRootWindow(window);
      return RootWindow.grayAuth?.satisfaction || false;
    },
    action() {
      return 'create'
    },
    linkmanPhone(){
      return this.query.phone
    },
    fields() {
      let originFields = this.initData.fieldInfo || []
      let sortedFields = originFields
        .sort((a, b) => a.orderId - b.orderId)
        .map(f => {
          if (f.formType === 'phone' && f.isSystem) {
            f.defaultValue = this.linkmanPhone
          }
          return f
        })
        .filter(f => {
          return (
            f.isNull == 0
            && f.fieldName !== 'serialNumber'
            && (f.fieldName !== 'tags' || (f.fieldName === 'tags' && this.initData.isDivideByTag))
            || (f.formType === 'address' && f.isSystem)
          )
        })
      return FormUtil.migration(sortedFields)
    },
    eventTypes() {
      if (!this.initData || (this.initData && !this.initData.eventTypeList))
        return []
      return this.initData.eventTypeList.map(t => Object.freeze(t))
    },
    taskTypes() {
      if (!this.initData || (this.initData && !this.initData.taskTypeList))
        return []
      return this.initData.taskTypeList.map(t => Object.freeze(t))
    },
    taskBusinessNo() {
      return (this.contact.taskBindRecord && this.contact.taskBindRecord.businessNo) || ''
    },
    eventBusinessNo() {
      return (this.contact.eventBindRecord && this.contact.eventBindRecord.businessNo) || ''
    },
    hasCallAuth() {
      return !!getRootWindow(window).CTI
    },
    allowEdit() {
      return this.globalIsHaveCallCenterEditAuth
    },
    auths() {
      return this?.initData?.auth ?? {};
    },
    allowCreateTask() {
      return AuthUtil.hasAuth(this.auths, 'TASK_ADD')
    },
    allowCreateEvent() {
      return AuthUtil.hasAuth(this.auths, 'CASE_ADD')
    },
    allowCreateCustomer() {
      return AuthUtil.hasAuth(this.auths, 'CUSTOMER_CREATE')
    },
  },
  async mounted() {
    query = parse(window.location.search) || {}
    this.query = query
    this.saveForm.phone = this.query.phone
    this.getCallRecord(query.id)
    this.getCustomerInfo()
    try {
      // 初始化默认值
      let form = {}
      form = util.packToForm(this.fields, form, this.initData.customerAddress)
      this.form = FormUtil.initialize(this.fields, form)
      this.init = true
    } catch (e) {
      console.error('CustomerEditView caught an error ', e)
    }
    this.getRemarkList()
    this.getCategoryList()
    this.getConversationInit();
  },
  methods: {
    getConversationInit() {
      const query = parse(window.location.search) || {};
      const id = query.id;
      this.iframeUrl = `/pcoperation/task/evaluate?id=${id}&fromCallcenter=true`;
    },
    audioPlay(type) {
      const trackIdObj = {
        record: 'CALL_RECORDING',
        leaveMessage: 'LISTEN_TO_CALL_MESSAGES',
      }
      this.$track.clickStat(this.$track.formatParams(trackIdObj[type]));
    },
    SetRequiredNotes(){},
    // 获取服务备注列表
    getRemarkList(){
      const params = {
        recordId: query.id
      }
      if(!query.id) return
      CallCenterApi.getFwRemarkList(params).then(({code, message, result}) => {
        if (code != 0) return this.$message.error(message || this.$t('callcenter.callCenter.innerError'))
        this.remarkList = result || []
      }).catch((err) => {
        console.error(err)
      })
    },
    // 获取咨询分类列表
    async getCategoryList(){
      CallCenterApi.getZxSortList().then(({code, message, result}) => {
        if (code !== 0) return this.$message.error(message || this.$t('callcenter.callCenter.innerError'))
        this.categoryList = result || []
      }).catch((err) => {
        console.error(err)
      })
    },
    // 选择项发生变化触发这个函数
    parentCateChanged() {
      // console.info('this.selectedKeys:', this.selectedKeys)
      // 如果 selectedKeys 数组中的 length 大于0，证明选中父级分类
      if (this.selectedKeys.length > 0) {
        this.ruleForm.sortId = this.selectedKeys[this.selectedKeys.length - 1]
      } else {
        this.ruleForm.sortId = 0
      }
    },
    async delRemark(item, index){
      try {
        if (!await this.$platform.confirm(this.$t('callcenter.callDetailPage.confirmDeleteRemark'))) return;
        const {code, message} = await CallCenterApi.deleteFwRemark({id:item.id})
        if (code !== 0) return this.$platform.notification({
          title: this.$t('common.base.tip.deleteFail'),
          message: message || '',
          type: 'error',
        });
        this.getRemarkList()
        this.$platform.notification({
          title: this.$t('common.base.tip.deleteSuccess'),
          type: 'success',
        });
      } catch (e) {
        console.error(e);
      }
    },
    // 保存备注
    saveRemark(formName) {
      this.$refs[formName].validate(async valid => {
        if (!valid) {
          return false
        }
        if(!query.id) return false
        const params = this.ruleForm
        params.recordId = query.id
        // console.info('params', params)
        try {
          const {code, message} = await CallCenterApi.saveFwRemark(params)
          if (code !== 0) return this.$platform.notification({
            title: this.$t('common.base.tip.saveFail'),
            message: message || '',
            type: 'error',
          })
          this.$refs[formName].resetFields()
          this.selectedKeys = []
          this.getRemarkList()
          this.$platform.notification({
            title: this.$t('common.base.tip.saveSuccess'),
            type: 'success',
          })
        } catch (e) {
          console.error(e)
        }
      })
    },
    // 通话信息
    getCallRecord(id) {
      if (!id) return
      CallCenterApi.getCallRecord({id}).then(({ code, message, result }) => {
        // 如果data为null说明是未知联系人
        if(code !== 0) return
        this.callDetail = result || {}
      }).catch((err) => {
        console.error(err)
      })
    },
    // 联系人信息
    getCustomerInfo() {
      if (!query.phone || !query.id) return
      CallCenterApi.getCustomerInfo({
        linkmanPhone: query.phone,
        callRecordId: query.id
      }).then(({ status, message, result }) => {
        // console.info('', status, message, result)
        // 如果data为null说明是未知联系人

        // 联系人和客户字段 有name则展示。事件按钮同理
        this.showLinkmanName = result && (result.name || result.linkman?.name) && !result.id;

        if (!result) {
          this.unknown = true
        } else {
          this.unknown = false
          this.customerId = result.id || ''
        }
        this.contact = result || {}
      }).catch((err) => {
        console.error(err)
      })
    },
    prettyAddress(adr = {}) {
      if (!adr) return ''
      return formatAddress(adr);
    },
    dealTags(tags = []) {
      const arr = []
      tags.forEach(item => arr.push(item.tagName))
      return arr.join('，')
    },
    saveDialogClosed() {
      this.$refs.saveFormRef.resetFields()
    },
    submit() {
      // console.info('form::', this.form);
      this.submitting = true
      this.$refs.form
        .validate()
        .then(valid => {
          this.submitting = false
          if (!valid) return Promise.reject('validate fail.')

          let params = util.packToCustomer(
            this.fields,
            this.form,
            this.initData.tags
          )

          params = this.globalFormSubmissionDataProcessingHandler(this.fields, params)

          this.pending = true
          this.loadingPage = true
          this.createMethod(params)
        })
        .catch(err => {
          console.error(err)
          this.pending = false
          this.loadingPage = false
        })
    },
    createMethod(params) {
      this.$http
        .post('/customer/create', params)
        .then(res => {
          let isSucc = !res.status
          platform.notification({
            type: isSucc ? 'success' : 'error',
            title: `${this.$t('callcenter.callDetailPage.createCustomer')}${isSucc ? this.$t('common.base.success') : this.$t('common.base.fail')}`,
            message: !isSucc && res.message
          })
          this.pending = false
          this.loadingPage = false

          if (!isSucc) return
          this.customerId = res.data.customerId
          // 是否还有后续动作
          // console.info('createMethod:', this.customerId)
          this.getCustomerInfo()
          this.showCreateUser = false;
        })
        .catch(err => console.error('err', err))
    },
    cancelCreate() {
      this.showCreateUser = false
    },
    saveUser() {
      this.$refs.saveFormRef.validate(async valid => {
        if (!valid) return
        const params = this.saveForm
        params.customerId = this.customer[0].value
        try {
          const { status, message } = await this.$http.post(
            '/linkman/save4Dialog',
            params
          )
          if (status !== 0)
            return this.$platform.notification({
              title: this.$t('common.base.tip.saveFail'),
              message: message || '',
              type: 'error'
            })
          this.$refs.saveFormRef.resetFields()
          this.saveDialogVisible = false
          this.$platform.notification({
            title: this.$t('common.base.tip.saveSuccess'),
            type: 'success'
          })
          this.getCustomerInfo()
        } catch (e) {
          console.error(e)
        }
      })
    },
    // 新建工单
    createTask(typeId) {
      if(this.showLinkmanName && this.bindProductId) {
        let fromId = window.frameElement.getAttribute('id')
        openAccurateTab({
          type: PageRoutesTypeEnum.PageCreateTaskFromProduct,
          key: this.bindProductId,
          params: `defaultTypeId=${typeId}&callRecordId=${query.id}&linkmanId=${linkmanId}`,
          fromId
        })
        return;
      }
      // console.info('typeId:', typeId);
      if (!this.customerId) return this.$message.error(this.$t('callcenter.callDetailPage.tips2'))
      let fromId = window.frameElement.getAttribute('id')
      const linkmanId = this.contact.linkman.id
      // this.$platform.openTab({
      //   id: 'createTask',
      //   title: '新建工单',
      //   close: true,
      //   url: `/task/edit4CallCenter?defaultTypeId=${typeId}&callRecordId=${query.id}&linkmanId=${linkmanId}`,
      //   fromId
      // })
      openAccurateTab({
        type: PageRoutesTypeEnum.PageCreateTaskFromCallCenter,
        params: `defaultTypeId=${typeId}&callRecordId=${query.id}&linkmanId=${linkmanId}`,
        fromId
      })
    },
    // 工单详情
    createTaskTab(taskId) {
      let fromId = window.frameElement.getAttribute('id')
      // this.$platform.openTab({
      //   id: `task_view_${taskId}`,
      //   title: '工单详情',
      //   close: true,
      //   url: `/task/view/${taskId}`,
      //   fromId
      // })
      openAccurateTab({
        type: PageRoutesTypeEnum.PageTaskView,
        key: taskId,
        fromId
      })
      this.$track.clickStat(this.$track.formatParams('TO_DETAIL_TASK'));
    },
    // 新建事件
    createEvent(typeId) {
      // console.info('typeId:', typeId);
      // if (!this.customerId) return this.$message.error(this.$t('callcenter.callDetailPage.tips2'))
      let fromId = window.frameElement.getAttribute('id')
      const linkmanId = this.contact?.linkman?.id || '';

      // 外部联系人信息添加。赋值给事件联系人、客户
      const customerName = this.contact?.name || '';
      const linkmanName = this.contact?.linkman?.name || '';
      const linkmanPhone = this.callDetail?.dialPhone || '';

      // this.$platform.openTab({
      //   id: 'createEvent',
      //   title: '新建事件',
      //   close: true,
      //   url: `/event/edit4CallCenter?defaultTypeId=${typeId}&callRecordId=${query.id}&linkmanId=${linkmanId}`,
      //   fromId
      // })
      openAccurateTab({
        type: PageRoutesTypeEnum.PageCreateEventFromCallCenter,
        params: `defaultTypeId=${typeId}&callRecordId=${query.id}&linkmanId=${linkmanId}&customerName=${customerName}&linkmanName=${linkmanName}&linkmanPhone=${linkmanPhone}&from=callcenter`,
        fromId
      })
    },
    // 事件详情
    createEventTab(eventId) {
      let fromId = window.frameElement.getAttribute('id')
      // this.$platform.openTab({
      //   id: `event_view_${eventId}`,
      //   title: '事件详情',
      //   close: true,
      //   url: `/event/view/${eventId}`,
      //   fromId
      // })
      openAccurateTab({
        type: PageRoutesTypeEnum.PageEventView,
        key: eventId,
        fromId
      })
      this.$track.clickStat(this.$track.formatParams('TO_DETAIL_EVENT'));
    },
    createCustomerTab(customerId) {
      let fromId = window.frameElement.getAttribute('id')
      // this.$platform.openTab({
      //   id: `customer_view_${customerId}`,
      //   title: '客户信息',
      //   close: true,
      //   url: `/customer/view/${customerId}?noHistory=1`,
      //   fromId
      // })
      openAccurateTab({
        type: PageRoutesTypeEnum.PageCustomerView,
        key: customerId,
        params: 'noHistory=1',
        fromId
      })
      this.$track.clickStat(this.$track.formatParams('TO_DETAIL_CUSTOMER'));
    },

    searchCustomer(params) {
      const pms = params || {}
      return getCustomerList(pms)
        .then(res => {
          if (!res || !res.list) return
          if (res.list) {
            res.list = res.list.map(customer =>
              Object.freeze({
                label: customer.name,
                value: customer.id
              })
            )
          }

          return res
        })
        .catch(e => console.error(e))
    },

    updateCustomer(value) {
      console.info('value:', value)
      this.customer = value
      this.$refs.saveFormRef.validateField('customer')
    },
    toCreateCustomer() {
      this.form.name = this.form.name || this.contact?.name || '';
      this.form.lmName = this.form.lmName || this.contact.linkman?.name || '';
      this.showCreateUser = true
      this.$track.clickStat(this.$track.formatParams('TO_CREATE_CUSTOMER'))
    },
    saveDialog(){
      this.saveForm.name = this.saveForm.name || this.contact.linkman?.name || '';
      this.saveDialogVisible = true
      this.$track.clickStat(this.$track.formatParams('ADD_TO_EXISTING_CUSTOMER'))
    }
  },
  components: {
    ServiceNotes,
    [CustomerEditForm.name]: CustomerEditForm,
    'customer-select': {
      name: 'customer-select',
      mixins: [FormMixin],
      props: {
        value: {
          type: Array,
          default: () => []
        },
        remoteMethod: Function,
        updateCustomer: Function,
        placeholder: String
      },
      methods: {
        input(value) {
          this.$emit('input', value)
        }
      },
      render(h) {
        return (
          <base-select
            value={this.value}
            placeholder={this.placeholder}
            remoteMethod={this.remoteMethod}
            onInput={this.updateCustomer}
          />
        )
      }
    },
    BaseCallPhone,
    CallcenterProductTable,
    CallcenterProductInfo,
    NoDataViewNew,
  }
}
</script>

<style lang="scss">
.audio__play--previous,
.audio__play--next {
  display: none;
}

.el-cascader-menus .el-cascader-menu__item{
  padding: 8px 15px;
  display: flex;
  line-height: 21px;
}
.el-cascader-menus .el-cascader-menu__item div{
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  max-width: 120px!important;
}

.call-center-detail-info {
  padding: 10px;
  display: flex;
  position: relative;
  box-sizing: border-box;
  min-height: 100vh;
  max-width: 100vw;
  .open-data {
    color: #333!important;
  }
  .main {
    flex: 1;
    background: #fff;
    padding: 12px;
    .call-info {
      display: flex;
      align-items: center;
      p {
        flex: 1;
        color: #999;
        span {
          color: #333;
        }
      }
    }

    .customer-info-header {
      margin-top: 20px;
      button {
        margin-left: 10px;
      }
    }

    .customer-info {
      p {
        color: #999;
        span {
          color: #333;
        }
      }
      img {
        width: 36px;
        height: 36px;
        border-radius: 50%;
        margin-right: 10px;
      }
      .unFinishTask,
      .unFinishEvent {
        /* @include fontColor(); */
      }

      .customer-container {
        .form-builder {
          padding: 0;
          .form-item {
            label {
              padding-left: 0 !important;
            }
            .input-and-btn {
              display: flex;
              button {
                margin-left: 10px;
                margin-right: 0px;
              }
            }
          }
        }
      }

      button {
        margin-right: 0px;
      }
    }
  }
  .right {
    max-height: 100vh;
    margin-left: 10px;
    width: 400px;
    background: #fff;
    padding: 12px;
    .item {
      margin-bottom: 10px;
      border-bottom: 1px solid #f5f5f5;
      .item-title {
        display: flex;
        justify-content: space-between;
        h4{
          font-size: 14px;
          margin-bottom: 10px;
          margin-left: 8px;
          font-weight: 600;
        }
      }
      .item-header {
        display: flex;
        align-items: center;
        p {
          flex: 1;
          margin-bottom: 10px;
          margin-left: 8px;
        }
      }
      .item-isDelete {
        display: flex;
        justify-content: space-between;
        color: #fb602c;
        height: 42px;
        font-size: 14px;
        line-height: 42px;
        .delete-time {
          color: #666;
          font-size: 12px;
        }
      }
      .item-content {
        padding: 5px;
        p {
          background-color: #fafbfc;
          padding: 10px;
          margin: 10px 0;
          color: #737f7b;
        }
        .el-tag--small {
          overflow: hidden;
        }
        .sort {
          width: 90px;
          white-space: nowrap;
          text-overflow: ellipsis;
          margin-right: 8px;
        }
      }
    }
    .el-textarea__inner{
      padding: 5px 10px;
    }

    .messagebox-content {
      overflow-y: auto;
      height: calc(100vh - 100px);
      padding: 10px;
      .iconfont-wrap {
        font-size: 12px;
        color: #262626;
        i {
          color: #13c2c2;
        }
        height: 30px;
        text-align: center;
        line-height: 30px;
      }
      .chat-content {
        padding-top: 20px;
        img {
          width: 36px;
          height: 36px;
        }
        font-size: 14px;
        .info {
          display: flex;
          .info-content {
            max-width: 300px;
            margin-left: 8px;
            padding: 8px 12px;
            border: 1px solid #eee;
            border-radius: 0 8px 8px 8px;
            word-wrap: break-word;
            color: #595959;
          }
        }
        .info-time {
          margin-left: 44px;
          font-size: 12px;
          margin-top: 5px;
          color: #bfbfbf;
        }
        .info-status {
          align-self: flex-end;
          font-size: 12px;
          color: #bfbfbf;
          margin-left: 4px;
        }
        .word-my {
          .info {
            display: flex;
            justify-content: flex-end;
            .info-status {
              margin-right: 4px;
            }
            .info-content {
              margin: 0 8px 0 0;
              background: rgba(19, 194, 194, 0.08);
              border: 1px solid rgba(0, 209, 178, 0.32);
              border-radius: 8px 0 8px 8px;
              color: #595959;
            }
          }
          .info-time {
            text-align: right;
            margin-right: 44px;
          }
        }
        .msg-img {
          width: 90px;
          height: 120px;
          margin-right: 10px;
          object-fit: contain;
        }
        .file-content {
          display: flex;
          max-width: 80%;
          padding: 10px;
          .file-img {
            width: 40px;
            height: 40px;
            margin-right: 10px;
          }
          p {
            margin-bottom: 4px;
          }
          a {
            color: #13c2c2 !important;
          }
        }
      }
    }
  }
}
.customer-info-a {
  color: $color-primary-light-5;
}
</style>

<style lang="scss" scoped>
::v-deep .el-tabs {
  height: auto;
}
</style>